<template>
  <div class="app-container">
    <!-- 查询条件区域-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="轨道编码" prop="map_num">
        <el-input size="small" v-model="queryParams.map_num" placeholder="请输入轨道编码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="轨道名称" prop="map_name">
        <el-input v-model="queryParams.map_name" placeholder="请输入轨道名称" clearable @keyup.enter.native="handleQuery"
          size="small" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!--增删改查按钮区域-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['ptwn:trackmap:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!--  数据列表区域-->
    <el-table v-loading="loading" :data="trackmapList" @selection-change="handleSelectionChange"
      :cell-style="{ borderColor: 'rgb(1 5 43)' }" :header-cell-style="{ borderColor: 'rgb(1 5 43)' }">
      <el-table-column label="机器人名称" align="center" prop="robot_name" width="200" />
      <el-table-column label="轨道编码" align="center" prop="map_num" :show-overflow-tooltip="true" />
      <el-table-column label="轨道名称" align="center" prop="map_name" width="310" />
      <el-table-column label="创建时间" align="center" prop="creater_time" width="250">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.creater_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleView(scope.row)"
            v-hasPermi="['ptwn:trackmap:query']">查看轨道图</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ptwn:trackmap:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--列表分页区域-->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" style="background:rgb(1 5 43);" />
    <!--添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" @close="handleCancle" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="88px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="机器人" prop="robot_config_id">
              <el-select v-model="form.robot_config_id" clearable placeholder="请选择机器人" @change="getOptionsjqr">
                <el-option v-for="item in robotList" :key="item.id" :label="item.robot_name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="轨道名称" prop="map_name">
              <el-input v-model="form.map_name" placeholder="请输入轨道名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="轨道类型" prop="map_id">
              <el-select v-model="form.map_id" placeholder="请选择轨道类型">
                <el-option v-for="dict in dict.type.map_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传底图">
              <el-upload class="upload-demo" ref="upload" action="" :limit="1" accept=".png,.jpg,.gif"
                :file-list="picList" :before-upload="beforeUpload1">
                <el-button slot="trigger" size="small" type="primary">选取只能900X500像素图片</el-button>
                <div slot="tip" class="el-upload-list__item-name">{{ picName }}</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上传文件">
              <el-upload class="upload-demo" ref="upload" action="" :limit="1" accept=".xml" :file-list="fileList"
                :before-upload="beforeUpload">
                <el-button slot="trigger" size="small" type="primary">选取电子轨道图XML文件</el-button>
                <div slot="tip" class="el-upload__tip" style="color:red">
                  openTCS缩放200%，按照轨迹顺序作图<div style="white-space: pre-wrap;">{{ "只能上传xml文件，且不超过10MB" }}</div>
                </div>
                <div slot="tip" class="el-upload__tip" style="color:red"></div>
                <div slot="tip" class="el-upload-list__item-name">{{ fileName }}</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" id="trackmapid" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--查看轨道图对话框-->
    <el-dialog :title="title" :visible.sync="open1" width="900px">
      <div id="container" ref="chinaMapChart" style="height:400px;"></div>
      <div slot="footer" class="dialog-footer">
        <el-form ref="form1" :model="form1" :rules="rules">
          <el-col :span="6">
            <el-form-item label="左移"><el-input-number v-model="form1.mleft" :precision="1" size="small"
                @change="mleftfun" /></el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="右移"><el-input-number v-model="form1.mright" :precision="1" size="small"
                @change="mrightfun" /></el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="上移"><el-input-number v-model="form1.mtop" :precision="1" size="small"
                @change="mtopfun" /></el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="下移"><el-input-number v-model="form1.mbottom" :precision="1" size="small"
                @change="mbottomfun" /></el-form-item>
          </el-col>
          <el-button type="primary" @click="submitForm1">保存设置</el-button>
          <el-button @click="open1 = false">关 闭</el-button>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import * as echarts from 'echarts';
import {
  addTrackMap,
  delTrackMap,
  getMapParamInfo,
  getTrackMap,
  listTrackMap,
  setMaparam
} from "@/api/ptwn/map/map";
import { listRobotConfig } from "@/api/ptwn/robotconfig/robotconfig";
import axios from "axios";
import Vue from "vue";
import $ from 'jquery';
import point from '@/assets/imgs/point1.png';
import rbt from '@/assets/images/rbt.png'
import "@/assets/styles/robt-bg.css";
import rbt1 from "@/assets/images/rbt1.png";
Vue.prototype.$http = axios;
let myChart = null;
export default {
  dicts: ['map_type'],
  data() {
    return {
      picpath: undefined,
      map_type: undefined,
      pics: undefined,
      ct: 0,
      arrdata: [[]],
      fileName: '',
      fileList: [],
      picName: '',
      calculatType: 'type',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      map_names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      picList: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 机器人列表
      robotList: [],
      // trackmap表格数据
      trackmapList: [],
      // 弹出层标题
      title: "",
      timer: null, // 定时器名称
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层
      open1: false,
      deract_dtop: [[]], deract_xposition: 0, deract_yposition: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 8,
        map_name: undefined,
        map_num: undefined
      },
      // 表单参数
      form: {
        robot_config_id: undefined,
        map_name: undefined,
        map_num: undefined,
        remark: undefined
      },//地图四个方向
      form1: {
        id: undefined,
        track_map_id: undefined,
        mleft: 0,
        mright: 0,
        mtop: 0,
        mbottom: 0
      },
      // 表单参数
      result: {
        map_name: undefined,
        map_num: undefined,
        remark: undefined,
        xyposition: undefined
      },
      // 表单校验
      rules: {
        map_name: [
          { required: true, message: "轨道名称不能为空", trigger: "blur" }
        ],
        robot_config_id: [
          { required: true, message: "机器人名称不能为空" }
        ],
        map_id: [
          { required: true, message: "轨道类型不能为空" }
        ]
      }
    };
  },
  created() {
    this.getList(); //地图列表
  },
  mounted() {
    this.timer = setInterval(() => {
      this.movepic();
    }, 1000)//1秒
  },
  beforeDestroy() {
    //清除定时器
    if(myChart != null){myChart.clear();myChart = null;}
    if (this.timer) {
      clearInterval(this.timer); //关闭
    }
  },
  methods: {
    //动态机器人图标方法
    movepic() {
      if (this.deract_dtop != "") {
        if (this.ct % 2 == 0)
          this.initEcharts(this.deract_dtop, this.deract_xposition, this.deract_yposition, this.form1.mleft, this.form1.mright, this.form1.mtop, this.form1.mbottom, 1);
        else
          this.initEcharts(this.deract_dtop, this.deract_xposition, this.deract_yposition, this.form1.mleft, this.form1.mright, this.form1.mtop, this.form1.mbottom, 2);
        this.ct += 1;
      }
    },
    //左移方法
    mleftfun(left) {
      this.mleft = left;
      this.mapderaction(left, this.mright, this.mtop, this.mbottom);
    },
    //右移方法
    mrightfun(right) {
      this.mright = right;
      this.mapderaction(this.mleft, right, this.mtop, this.mbottom);
    },
    //上移方法
    mtopfun(top) {
      this.mtop = top;
      this.mapderaction(this.mleft, this.mright, top, this.mbottom);
    },
    //下移方法
    mbottomfun(bottom) {
      this.mbottom = bottom;
      this.mapderaction(this.mleft, this.mright, this.mtop, bottom);
    },
    //自定义对话框关闭方法
    handleCancle() {
      $("#trackmapid").css("display", "");
      this.picpath = null;
      this.fileName = null;
      this.files = null;
      this.picName = null;
      this.pics = null;
        this.$refs.form.resetFields()
      this.dialogVisible = false
    },
    //上传附件
    beforeUpload(file) {
      //console.log(file,'文件');
      this.files = file;
      const extension = file.name.split('.')[1] === 'xml'
      const isLt2M = file.size / 1024 / 1024 < 20
      if (!extension) {
        this.fileName = null;
        this.files = null;
        this.$message.warning('上传只能是xml格式!')
        return false // 返回false不会自动上传
      }
      if (!isLt2M) {
        this.fileName = null;
        this.files = null;
        this.$message.warning('上传大小不能超过 20MB!')
        return false // 返回false不会自动上传
      }
      this.fileName = file.name;
      return false // 返回false不会自动上传
    },
    //上传图片
    beforeUpload1(pic) {
      /* console.log(pic,'文件');*/
      this.pics = pic;
      const extension = (pic.name.split('.')[1] === 'png') || (pic.name.split('.')[1] === 'gif') || (pic.name.split('.')[1] === 'jpg')
      const isLt2M = pic.size / 1024 / 1024 < 2
      if (!extension) {
        this.picName = null;
        this.pics = null;
        this.$message.warning('上传只能是png|gif|jpg格式!')
        return false // 返回false不会自动上传
      }
      if (!isLt2M) {
        this.picName = null;
        this.pics = null;
        this.$message.warning('上传大小不能超过 2MB!')
        return false // 返回false不会自动上传
      }
      this.picName = pic.name;
      return false // 返回false不会自动上传
    },
    /** 查询机器人列表 */
    getrobotList() {
      listRobotConfig(this.queryParams).then(response => {
        this.robotList = response.rows;
      });
    },
    /** 查询电子轨道图列表 */
    getList() {
      this.loading = true;
      listTrackMap(this.queryParams).then(response => {
        this.trackmapList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //根据机器人id查询是否关联轨道图
    getOptionsjqr(id) {
      this.queryParams.robot_config_id = id;//设置站点id条件，查询工艺体
      listTrackMap(this.queryParams).then(response => {
        if (typeof (response) != "undefined" && response != null && response.rows.length > 0) {
          $("#trackmapid").css("display", "none");
          this.$modal.confirm1('当前机器人已关联轨道图！');
          this.queryParams.robot_config_id = null;
        } else {
          $("#trackmapid").css("display", "");
          this.queryParams.robot_config_id = null;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        creater_id: undefined,
        creater_time: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.map_names = selection.map(item => item.map_name)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增电子轨道图";
      this.getrobotList();//机器人列表
    },
    /*手动调整地图位置方法*/
    mapderaction(mleft, mright, mtop, mbottom) {
      this.initEcharts(this.deract_dtop, this.deract_xposition, this.deract_yposition, mleft, mright, mtop, mbottom, 1);
    },
    /** 查看电子轨道图方法*/
    handleView(row) {
      this.reset();
      const id = row.id || this.ids;
      this.picpath = row.pic_url;
      getTrackMap(id).then(response => {
        if (response != null && response.data.length > 0) {
          this.result = response.data;
          this.open1 = true;
          this.title = "电子轨道图";
          this.arrdata = [[]];//初始化地图值
          //轨道地图数据
          let robotxy = this.result[0].xyposition.split(",");//机器人开始位置x坐标
          let xposition = robotxy[0];//机器人开始位置x坐标
          let yposition = robotxy[1];//机器人开始位置y坐标
          this.deract_xposition = robotxy[0];//机器人开始位置x坐标
          this.deract_yposition = robotxy[1];//机器人开始位置y坐标
          for (let x = 0; x < this.result.length; x++) {
            //因为在后台取出来的数据是一行的，字符串形式
            let dataArray = this.result[x].xyposition.split(",");
            //这句话是必须的，每次都要新建一个一维数组,不然会报错
            this.arrdata[x] = new Array();
            for (let i = 0; i < dataArray.length; i++) {
              this.arrdata[x][i] = dataArray[i];
            }
          }
          const dtop = this.arrdata;
          this.deract_dtop = this.arrdata;
          getMapParamInfo(id).then(response => {
            if (response != null && response.data != null) {
              this.form1.id = response.data.id;
              //展示地图四个位移方向
              this.form1.mleft = response.data.mleft;
              this.form1.mright = response.data.mright;
              this.form1.mtop = response.data.mtop;
              this.form1.mbottom = response.data.mbottom;
              this.form1.track_map_id = id;
              //调用电子地图
              this.initEcharts(dtop, xposition, yposition, response.data.mleft, response.data.mright, response.data.mtop, response.data.mbottom, 1);
            } else { //默认方向
              this.initEcharts(dtop, xposition, yposition, 0, 0, 0, 0, 1);
            }
          });
        }
      });
    },
    /*电子轨道图方法*/
    initEcharts(dtop, xposition, yposition, mleft, mright, mtop, mbottom, fg) {
      setTimeout(() => {
        myChart = echarts.init(this.$refs.chinaMapChart)
        let option;
        //轨道地图数据
        const data = dtop;
        let img = document.createElement('img');
        img.src = (this.picpath == null || this.picpath == '') ? require('@/assets/images/map-default.png')
          : this.picpath;
        option = {
          tooltip: {
            trigger: 'item',
            formatter: (params) => {  // params就是数据，这里可以打印一下看看
              // return 出去什么，鼠标移入就显示什么,marker就是提示前面蓝色的圆点
              if (typeof params.data[0] == 'undefined') {
                return ``
              } else {
                return `${params.data[2]}</br>${params.marker}横坐标:${params.data[0]}</br>纵坐标:${params.data[1]}`
              }
            }
          },
          /*  backgroundColor: {
               type: 'pattern',
               repeat: 'no-repeat',
               image: img, // 轨道图底图
            },*/
          //backgroundColor:'#d0defa',//地图背景色
          title: {
            /* text: '机器人巡检轨迹图',*/
            left: 'center'
          },
          grid: {//底图四个方向调整
            top: mtop + '%',
            bottom: mbottom + '%',
            left: mleft + '%',
            right: mright + '%'
          },
          xAxis: {
            splitLine: { //网格线
              show: false
            },
            type: 'value',
            axisLine: {
              onZero: false,
              show: false//隐藏y轴
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              show: false, //隐藏刻度值
            }
          },
          yAxis: {
            splitLine: { //网格线
              show: false
            },
            type: 'value',
            axisLine: {
              onZero: false,
              show: false//隐藏y轴
            },
            axisTick: {
              show: false,  //刻度线
            },
            axisLabel: {
              show: false, //隐藏刻度值
            }
          },
          series: [
            {
              label: {
                color: '#cefc04',
                show: true,
                position: "top",
                formatter: '{@value}',// 点旁边显示label，这里使用name: '横坐标'这样写也可以，鼠标移入出现提示。
              },
              id: 'a',
              /* type: (this.picpath == null || this.picpath == '') ? 'line':'scatter',//scatter 散点，line 曲线*/
              type: 'line',
              smooth: true,
              itemStyle: {
                // 设置线条颜色
                normal: {
                  color: (this.picpath == null || this.picpath == '') ? '#1446a2' : 'rgb(18,41,213)',
                  lineStyle: {
                    width: (this.picpath == null || this.picpath == '') ? 5 : 5,
                    type: (this.picpath == null || this.picpath == '') ? 'solid' : 'solid'//可选值还有 dotted  solid
                  }
                }
              },
              symbolSize: 14,//巡检点大小
              symbol: 'image://' + point,//巡检点图标
              data: data,
              //  symbol: 'circle',
              markPoint: {
                label: {
                  color: 'blue',  // 文字颜色
                  // padding: [0, 0,-10, 0], // 可用padding调整图片内文字距离
                  show: true,
                  //formatter: '巡检机器人'// 自定义文字内容
                },
                //机器人大小
                itemStyle: {
                  color: {
                    type: 'linear',
                    colorStops: [{
                      offset: 0, color: 'blue' // 0% 处的颜色
                    }, {
                      offset: 1, color: 'blue' // 100% 处的颜色
                    }]
                  }
                },
                //symbol: 'circle',
                symbol: fg == 1 ? 'image://' + rbt : 'image://' + rbt1,
                // 自定义图片作为标注展示
                // symbolSize: [58, 38],  // 调整图片的长宽
                // symbolOffset: [10, '-50%'],  // 调整标注图片的位移方向 大小
                symbolSize: 18,//机器人大小
                data: [{//1机器人移动坐标位置
                  xAxis: xposition,
                  yAxis: yposition,
                } /*,{//2机器人移动坐标位置
                  xAxis:23000,
                  yAxis:21500,
                }*/],
              }
            },
            // 闪烁点的重点是以下配置
            {
              // 设置圆心点特效动画、大小
              type: 'effectScatter', data: dtop,
              symbolSize: 6,
              coordinateSystem: 'cartesian2d',
              // 何时显示特效:'render'-绘制完成后显示特效 'emphasis'-高亮（hover）的时候显示特效
              showEffectOn: 'render',
              // 涟漪特效配置
              rippleEffect: {
                color: '#1229d5',
                scale: 4,
                // 波纹的绘制方式,可选'stroke'和'fill'
                brushType: 'stroke'
              },
              //圆心点
              hoverAnimation: true,
              itemStyle: {
                normal: {
                  color: '#1229d5',
                  shadowBlur: 80,
                  shadowColor: '#3a86ea',
                }
              },
              zlevel: 1
            }
          ], graphic: [
            {
              type: 'image', // 图形元素类型
              id: 'logo', // 更新或删除图形元素时指定更新哪个图形元素，如果不需要用可以忽略。
              right: 'center', // 根据父元素进行定位 （居中）
              bottom: '0%', // 根据父元素进行定位   （0%）, 如果bottom的值是 0，也可以删除该bottom属性值。
              z: 0,  // 层叠
              bounding: 'all', // 决定此图形元素在定位时，对自身的包围盒计算方式
              style: {
                image: img, // 这里一定要注意、注意，必须是https开头的图片路径地址
                width: 800,
                height: 400
              }
            }
          ]
        }
        if (option && typeof option === 'object') {
          myChart.setOption(option);
        }
        window.addEventListener("resize", () => {
          if(myChart!=null)myChart.resize();
        });//同比缩放
        // 点击方法
        myChart.on('click', function (params) {
          // 控制台打印数据的名称
        });
        /*  window.addEventListener('resize', myChart.resize);*///电子地图与背景图同比缩放
      }, 1);
    },
    /** 提交按钮 */
    submitForm: function () {
      //console.log('上传'+this.files.name)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.fileName == "") {
            this.$message.warning('请选择要上传的文件！')
            return false
          }
          const formData = new FormData();
          formData.append('file', this.files);//filename是键，file是值，就是要传的文件，test.zip是要传的文件名
          formData.append('pic', typeof this.pics == "undefined" ? null : this.pics);
          //轨道图实体参数
          formData.append("robot_config_id", this.form.robot_config_id);
          formData.append("map_num", this.form.map_num);
          formData.append("map_name", this.form.map_name);
          formData.append("remark", this.form.remark);
          formData.append("map_id", this.form.map_id);
          addTrackMap(formData).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm1: function () {
      this.$refs["form1"].validate(valid => {
        if (valid) {
          setMaparam(this.form1).then(response => {
            this.$modal.msgSuccess("设置成功！");
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const map_names = row.map_name || this.map_names;
      this.$modal.confirm('是否确认删除轨道名称为"' + map_names + '"的数据项？').then(function () {
        const formData = new FormData();
        formData.append('ids', row.id || this.ids);
        formData.append('picpath', row.pic);
        return delTrackMap(formData);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
.el-input--small .el-input__inner {
  border-color: #195083;
  height: 32px;
  line-height: 32px;
  background-color: #0e2356;
}

.el-input-number__decrease {
  border-color: #0e2356;
}
</style>
